package com.panopset.gui.container;

import static com.panopset.Util.*;

import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Vector;

import javax.swing.JFileChooser;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.panopset.app.panopset.Application;
import com.panopset.gui.TButton;
import com.panopset.gui.TPanel;

/**
 * File path persistent container.
 *
 * @author Karl Dinwiddie
 *
 */
public class PanFile extends PanField<JPanel> {

    public static void main(String... s) {
        new Application() {

            @Override
            protected JPanel createMainPanel() {
                JPanel p = new JPanel();
                p.setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 2;
                gbc.gridy = 0;
                gbc.fill = GridBagConstraints.HORIZONTAL;
                gbc.weightx = 1.0;
                p.add(new PanFile("test", "testing").getPanel(), gbc);
                p.setBackground(Color.YELLOW);
                return p;
            }
        }.setVisible(true);
    }

    public PanFile(String borderTitle, String toolTipText) {
        this(borderTitle, toolTipText, EMPTY_STRING);
    }

    public PanFile(String borderTitle, String toolTipText,
            String defaultValue) {
        this(borderTitle, toolTipText, defaultValue, false);
    }

    protected PanFile(String borderTitle, String toolTipText,
            String defaultValue, boolean isDirectory) {
        super(borderTitle, toolTipText, defaultValue);
        getPanel().setLayout(new GridLayout(1, 1));
        this.isDirectory = isDirectory;
    }
    private String borderTitle = EMPTY_STRING;
    private String description = EMPTY_STRING;
    private final boolean isDirectory;
    private final Vector<UpdateListener> updateListeners = new Vector<UpdateListener>();

    public void addUpdateListener(UpdateListener updateListener) {
        updateListeners.add(updateListener);
    }

    private void update() {
        for (UpdateListener updateListener : updateListeners) {
            updateListener.update();
        }
    }

    @Override
    public String getComponentValue() {
        return getFileTextField().getText();
    }

    @Override
    public void setComponentValue(String value) {
        getFileTextField().setText(value);
        update();
    }

    public void setSelectedFile(File file) {
        if (file != null && file.exists()) {
            getFileTextField().setText(getCanonicalPath(file));
            update();
        }
    }

    public File getFile() {
        String path = getFileTextField().getText();
        return path == null ? null : EMPTY_STRING.equals(path.trim()) ? null
                : new File(path);
    }

    void doBrowse() {
        setSelectedFile(fileDialog(JFileChooser.OPEN_DIALOG));
    }

    void doNew() {
        setSelectedFile(fileDialog(JFileChooser.SAVE_DIALOG));
        File f = getFile();
        if (f == null || EMPTY_STRING.equals(getCanonicalPath(f))) {
            dspmsg(x("No file selected."));
            return;
        }
        if (isDirectory) {
            mkdirs(f);
        } else {
            try {
                FileWriter fw = new FileWriter(f);
                fw.write(EMPTY_STRING);
                fw.flush();
                fw.close();
            } catch (IOException e) {
                log(e);
            }
        }
    }

    private File fileDialog(int dialogType) {
        File rtn = null;
        File dftPath = new File(getCanonicalPath(new File("x"))).getParentFile();
        JFileChooser chooser = new JFileChooser();
        if (EMPTY_STRING.equals(getFileTextField().getText().trim())) {
            if ((dftPath != null) && (getCanonicalPath(dftPath).length() > 0)) {
                chooser.setSelectedFile(dftPath);
            }
        } else {
            chooser.setSelectedFile(getFile());
        }
        chooser.setFileSelectionMode(isDirectory ? JFileChooser.DIRECTORIES_ONLY
                : JFileChooser.FILES_ONLY);
        chooser.setDialogTitle(getPrompt());
        chooser.setDialogType(JFileChooser.SAVE_DIALOG);
        if (chooser.showOpenDialog(getParentFrame()) == JFileChooser.APPROVE_OPTION) {
            rtn = chooser.getSelectedFile();
        }
        if (rtn != null) {
            getFileTextField().setText(getCanonicalPath(rtn));
        }
        update();
        return rtn;
    }

    public JPanel createGui() {
        return getPanel();
    }
    private TPanel panel;

    @Override
    public TPanel createComponent() {
        String requiredPrompt = isDirectory ? x("directory required")
                : x("file required");
        panel = new TPanel.Builder().borderTitle(borderTitle).tip(
                x("Select") + SINGLE_SPACE + description).layout(
                new GridBagLayout()).requiredPrompt(requiredPrompt).construct();

        GridBagConstraints gbc = null;

        TButton btn = new TButton(x("New"), KeyEvent.VK_N, x("Create new") + SINGLE_SPACE + description, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                doNew();
            }
        });
        gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0;
        panel.add(btn, gbc);
        btn = new TButton(x("Browse"), KeyEvent.VK_B, x("Browse for") + SINGLE_SPACE + description, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                doBrowse();
            }
        });
        gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.weightx = 0;
        panel.add(btn, gbc);
        gbc = new GridBagConstraints();
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;

        panel.add(getFileTextField(), gbc);
        return panel;
    }
    private JTextField fileTextField;

    private JTextField getFileTextField() {
        if (fileTextField == null) {
            fileTextField = new JTextField(10);
        }
        return fileTextField;
    }
    private String prompt;

    private String getPrompt() {
        if (prompt == null) {
            prompt = x("Please select a ") + (isDirectory ? x("directory") : x("file"));
        }
        return prompt;
    }
}
